package com.example.gybicycle.controller.web;
import  com.alibaba.fastjson.JSON;

import com.example.gybicycle.entity.Active;
import com.example.gybicycle.service.FileService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.example.gybicycle.common.Log.SysLoging;
import com.example.gybicycle.common.entity.NormalPage;
import com.example.gybicycle.common.entity.Result;
import com.example.gybicycle.common.util.*;
import com.example.gybicycle.entity.Bike;
import com.example.gybicycle.entity.LoginInfo;
import com.example.gybicycle.entity.SysUser;
import com.example.gybicycle.service.BikeService;



@Tag(name = "车辆")
@RestController
@RequestMapping("/web/bike")
public class BikeController {
    @Autowired
    private BikeService bikeService;
    @Autowired
    private FileService fileService;
    @PostMapping("/get")
    @SysLoging("车辆管理-查看")
    @Operation(summary = "根据id查看")
    @RequiresPermissions("bike:list")
    @ApiOperationSupport(includeParameters = {"bike.id"})
    public Result get(@RequestBody Bike bike){
      bike=bikeService.get(bike.getId());
        return Result.success(bike);
    }
    @PostMapping("/list")
    @Operation(summary =  "列表查看")
    @ApiOperationSupport(includeParameters = {"page.id","page.page","page.size","page.name","bike.state"})
    @RequiresPermissions("bike:list")
    @SysLoging("车辆管理-查看")
    public Result findList(@RequestBody(required=false)  Bike page){
       
        Page<Bike> list = PageHelper.startPage(page.getPage(), page.getSize()).doSelectPage(
                () ->bikeService.findList(page));
        return Result.success(NormalPage.createPage(list));
    }
    @GetMapping(value = "/download",produces = "application/octet-stream")
    @Operation(summary =  "下载")
//    @ApiImplicitParam(paramType = "query",name = "startTime", value = "时间[yyyy-MM-dd HH:mm:ss]", dataType = "Date",defaultValue = "2019-03-14 14:00:00")
    public void download(Bike bike, HttpServletRequest request, HttpServletResponse response) throws IOException {
        LoginInfo info=LoginUtil.getLoginInfo(request);
        if(info==null)
            return  ;
        if(bike==null)
            bike=new Bike();
        var paths=bikeService.findCode(bike);
        String zip=fileService.downLoadBikeQRCode(paths);
        File file=new File(zip);
        // 设置响应头信息
        String filename = file.getName();
        // 文件转成字节数组
        byte[] fileByte = Files.readAllBytes(file.toPath());
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        // 指定下载文件名(attachment-以下载方式保存到本地，inline-在线预览)
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        // 告知浏览器文件的大小
        response.addHeader("Content-Length", "" + file.length());
        // 内容类型为通用类型，表示二进制数据流
        response.setContentType("application/octet-stream");
        OutputStream os = response.getOutputStream();
        os.write(fileByte);
        os.flush();
 }
    @PostMapping(value = "/download2")
    @Operation(summary =  "下载2")
//    @ApiImplicitParam(paramType = "query",name = "startTime", value = "时间[yyyy-MM-dd HH:mm:ss]", dataType = "Date",defaultValue = "2019-03-14 14:00:00")
    public Result download2(@RequestBody Bike bike, HttpServletRequest request) {
        LoginInfo info=LoginUtil.getLoginInfo(request);
        if(info==null)
            return  null;
        if(bike==null)
            bike=new Bike();
        var paths=bikeService.findCode(bike);
        String zip=fileService.downLoadBikeQRCode2(paths);
        if(zip==null)
            return Result.fail("下载失败");
        return Result.success(zip,"SUCCESS");
    }
    @PostMapping("/insert")
    @Operation(summary =  "添加")
    @RequiresPermissions("bike:insert")
    @SysLoging("车辆管理-添加")
    public Result insert(@RequestBody Bike bike, HttpServletRequest request){
         LoginInfo loginInfo=LoginUtil.getLoginInfo(request);
        if(loginInfo==null)
            return Result.loginOut();
        bike.setEditBy(loginInfo.getUser().getId());
        bike.setEditTime(new Date());
        if(bike.getLatchNo()!=null&&bike.getLatchNo().length()>0){
            Bike us=new Bike();
            us.setLatchNo(bike.getLatchNo());
            int count =bikeService.count(us);
            if(count>0)
                return Result.fail("当前插销已录入");
        }

        int num=bikeService.insert(bike);
        return Result.reData(num,bike);
    }
    @PostMapping("/update")
    @Operation(summary =  "修改")
    @RequiresPermissions("bike:update")
    @SysLoging("车辆管理-修改")
    public Result update(@RequestBody Bike bike, HttpServletRequest request){
        LoginInfo loginInfo=LoginUtil.getLoginInfo(request);
        if(loginInfo==null)
            return Result.loginOut();
        bike.setEditBy(loginInfo.getUser().getId());
        bike.setEditTime(new Date());
        if(bike.getLatchNo()!=null&&bike.getLatchNo().length()>0) {
            Bike us = new Bike();
            us.setLatchNo(bike.getLatchNo());
            List<Bike> count = bikeService.findList(us);
            if ((count.size() > 1) || (count.size() == 1 && !count.get(0).getId().equals(bike.getId())))
                return Result.fail("当前插销已录入");
        }
        int num=bikeService.update(bike);
        return Result.reData(num,bike);
    }
  @PostMapping("/delete")
    @Operation(summary =  "删除")
    @RequiresPermissions("bike:delete")
    @SysLoging("车辆管理-删除")
    public Result delete(@RequestBody Bike entity){
        int num=bikeService.delete(entity.getId());
        if(num>0)
            return Result.success("删除成功");
        else 
            return Result.fail("删除失败");
    }
     @PostMapping("deletelist")
    @Operation(summary =  "批量删除")
    @ApiOperationSupport(includeParameters = {"bike.id"})
    @RequiresPermissions("bike:delete")
    @SysLoging("车辆管理-批量删除")
    public Result deletelist(@RequestBody List<String> data){
        int num=bikeService.deleteByBatch(data);
         if(num>0)
             return Result.success("删除成功");
         else
             return Result.fail("删除失败"); 
    }
}